const {mockHistoryMenus} = require('../../mock/menu');

Page({
  data: {
    historyMenus: [
      {
        id: 1,
        date: '2025-04-28 晚餐',
        summary: '红烧肉x2、清炒时蔬x1、番茄炒蛋x1',
        remark: '今晚有小朋友，少放辣椒'
      },
      {
        id: 2,
        date: '2025-04-27 午餐',
        summary: '宫保鸡丁x1、鱼香茄子x1、紫菜蛋花汤x1',
        remark: '多做点素菜'
      },
      {
        id: 3,
        date: '2025-04-26 晚餐',
        summary: '糖醋里脊x2、蒜蓉西兰花x1',
        remark: '无'
      }
    ]
  },

  onLoad(options) {
    // 检查是否是查看今日菜单
    const viewToday = options && options.viewToday === 'true';

    if (viewToday) {
      // 获取今日菜单
      const todayMenu = wx.getStorageSync('todayMenu');
      if (todayMenu) {
        const formattedMenu = {
          id: todayMenu.id || Date.now(),
          date: todayMenu.date || '今日',
          summary: this.formatSummary(todayMenu.dishes),
          remark: todayMenu.remark || '无',
          isToday: true
        };

        this.setData({
          historyMenus: [formattedMenu],
          viewingToday: true
        });
        return;
      }
    }

    // 获取本地存储的历史菜单
    const historyMenus = wx.getStorageSync('historyMenus') || [];

    if (historyMenus.length > 0) {
      // 将历史菜单转换为页面需要的格式
      const formattedMenus = historyMenus.map(menu => {
        return {
          id: menu.id || Math.random().toString(36).substr(2, 9),
          date: menu.date,
          summary: this.formatSummary(menu.dishes),
          remark: menu.remark || '无'
        };
      });

      this.setData({
        historyMenus: formattedMenus
      });
    }
    // 如果没有本地存储的历史菜单，使用mock数据
    else if (mockHistoryMenus && mockHistoryMenus.length > 0) {
      // 将mock数据转换为页面需要的格式
      const formattedMenus = mockHistoryMenus.map(menu => {
        return {
          id: menu.id || Math.random().toString(36).substr(2, 9),
          date: menu.date,
          summary: this.formatSummary(menu.dishes),
          remark: menu.remark || '无'
        };
      });

      this.setData({
        historyMenus: formattedMenus
      });
    }
  },

  // 格式化菜品摘要
  formatSummary(dishes) {
    if (!dishes || !dishes.length) {
      return '暂无菜品';
    }

    return dishes.map(dish => `${dish.name}x${dish.count}`).join('、');
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  }
});
